<?php

namespace app\astroapp\controller;

use app\common\lib\exception\ApiException;
use app\common\lib\IAuth;
use think\Controller;
use think\Log;

class AstroAppRemoteAuth extends Controller
{
    /**
     * headers信息
     * @var array
     */
    public $headers = [];

    protected function _initialize()
    {
        $this->checkRequestAuth();
    }

    /**
     * 检查每次app请求的数据是否合法
     * @throws ApiException
     */
    public function checkRequestAuth()
    {
        // 首先需要获取headers
        $headers = $this->request->header();

        if (!defined('IS_ACCESS_TOKEN_CHECKED'))
        {
            try
            {
                if (!isset($headers['app']) || $headers["app"] !== 'astro_app_remote')
                {
                    throw new ApiException('当前设备不支持');
                }
                $key = '8Yrrebpj8T0Wwm0h2YwQ';
                $d = [
                    'app' => $headers["app"],
                    'app-type' => $headers["app-type"],
                    'time' => $headers['time'],
                    'version' => $headers['version'],
                    'id' => $headers['id'],
                ];
                $d = $key . '&' . http_build_query($d);
                if (!isset($headers['sign']) || $headers['sign'] !== md5($d))
                {
                    throw new ApiException('接口请求失败');
                }
                // 1、文件  2、mysql 3、redis   由于服务器为集群架构   此处使用redis
                define('IS_ACCESS_TOKEN_CHECKED', true);
            }
            catch (\Exception $e)
            {
                throw new ApiException('接口请求失败');
            }
        }
        // 将当前请求头信息存入header属性中，以便后面使用
        $this->headers = $headers;
    }
}